package com.gm.wholesale.module.settlement.ui.tab;

import android.text.InputFilter;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import com.gm.commonlib.base.baseAdapter.CommonAdapter;
import com.gm.commonlib.base.baseAdapter.ViewHolder;
import com.gm.commonlib.base.baseBean.BasePageData;
import com.gm.commonlib.base.baseBean.BasePageListData;
import com.gm.commonlib.base.baseBean.BaseResp;
import com.gm.commonlib.base.baseView.IBaseView;
import com.gm.commonlib.base.baseui.baseListviewUI.BaseGridFragment;
import com.gm.commonlib.network.BaseHttpObserver;
import com.gm.commonlib.network.HttpServicesHolder;
import com.gm.commonlib.util.numberUtils.NumberUtils;
import com.gm.commonlib.util.timeUtils.DateTimeUtils;
import com.gm.commonlib.views.dialog.DialogUtil;
import com.gm.commonlib.views.dialog.InputDialog;
import com.gm.commonlib.views.toast.ToastUtil;
import com.gm.wholesale.R;
import com.gm.wholesale.constant.Constant;
import com.gm.wholesale.module.settlement.api.IReconciliationApi;
import com.gm.wholesale.module.settlement.bean.WaitToAccuntBean;
import com.gm.wholesale.module.settlement.model.ReconciliationMode;
import com.gm.wholesale.module.settlement.view.AccuntHeaderView;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Observable;

public class WaitToAccuntListFragment extends BaseGridFragment<WaitToAccuntBean, BasePageData<WaitToAccuntBean>> {


    private AccuntHeaderView accuntHeaderView;
    private String startTime;
    private String endTime;

    private long customerId;

    public void updateView(){
        mChoices.clear();
        startTime=null;
        endTime=null;
        accuntHeaderView.reset();
        refreshData();
    }



    public void setCustomerId(long customerId) {
        this.customerId = customerId;
    }

    private List<WaitToAccuntBean> mChoices = new ArrayList<>();

    @Override
    public void initPullToRefreshListView() {
        super.initPullToRefreshListView();
        mGridView.setNumColumns(2);
        mGridView.setHorizontalSpacing(15);
        mGridView.setVerticalSpacing(15);
    }

    @Override
    public void getDataOnCompleted() {
        super.getDataOnCompleted();
        showCheckBox();
    }

    @Override
    public void refreshData() {
        super.refreshData();
        mChoices.clear();

    }

    @Override
    protected BaseAdapter createTempBaseAdapter() {
        return new CommonAdapter<>(getActivity(), mDatas, R.layout.list_wait_to_accunt_item) {
            @Override
            public void convert(ViewHolder viewHolder, final WaitToAccuntBean data) {
                CheckBox checkBox = viewHolder.getView(R.id.choiceBox);
                if (data.ismIsCheck()) {
                    checkBox.setButtonDrawable(R.drawable.gou_check);
                } else {
                    checkBox.setButtonDrawable(R.drawable.gou_uncheck);
                }
                checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> getChoiceData(data));
                viewHolder.getConvertView().setOnClickListener(v -> getChoiceData(data));
                viewHolder.setText(R.id.createTimeTv, "下单时间：" + data.getCreateTime());
                viewHolder.setText(R.id.numTv, data.getNo());
                double price=data.getAmount();
                //售后单子
                if (data.getType()==2){
                    viewHolder.setText(R.id.priceTv, "退款金额：" + NumberUtils.getMoneyString(data.getAmount()));
                }
                else {
                    viewHolder.setText(R.id.priceTv, "销售金额：" + NumberUtils.getMoneyString(data.getAmount()));
                }

            }
        };
    }

    private void getChoiceData(WaitToAccuntBean data) {
        if (data.ismIsCheck()) {
            mChoices.remove(data);
        } else {
            mChoices.add(data);
        }
        data.setmIsCheck(!data.ismIsCheck());
        showCheckBox();
        notifyListDataSetChanged();
    }

    private void showCheckBox() {
        if (mChoices.size() == mDatas.size() && mDatas.size()>0) {
            accuntHeaderView.setAllChecked(true);
        } else {
            accuntHeaderView.setAllChecked(false);
        }
    }

    @Override
    protected void onCreateContentHeader(ViewGroup parent) {
        super.onCreateContentHeader(parent);
        accuntHeaderView = new AccuntHeaderView(getContext());
        parent.addView(accuntHeaderView);
        accuntHeaderView.setOnFunctionListener(new AccuntHeaderView.OnFunctionListener() {
            @Override
            public void onAllChecked(boolean isCheck) {
                updateView(isCheck);
            }

            @Override
            public void onToAccount() {
                if (mChoices.isEmpty()) {
                    ToastUtil.showToast("请先选择订单");
                    return;
                }
                showToAccountDialog();
            }

            @Override
            public void onChoiceTime(Date startTimeData, Date endTimeData) {
                startTime = DateTimeUtils.formatDateTime(startTimeData, DateTimeUtils.YMD);
                startTime = startTime + " 00:00:00";
                endTime = DateTimeUtils.formatDateTime(endTimeData, DateTimeUtils.YMD);
                endTime = endTime + " 23:59:59";
                refreshData();
            }
        });
    }

    private void showToAccountDialog() {
        String content = accuntHeaderView.choiceTimeTv.getText() + "的对账单";
        content = content.replaceAll(" ", "");
       InputDialog dialog=  DialogUtil.showInputDialog(getContext(), "生成对账单", content, (inputData, inputDialog) -> {
             if (TextUtils.isEmpty(inputData)) {
                 ToastUtil.showToast("对账名称不能为空");
                 return;
             }
             inputDialog.dismiss();
             HashMap<String, Object> data = new HashMap<>();
             data.put("name", inputData);
             data.put("customerSettlementDetailIds", getOrderId());
             ReconciliationMode.createOrder((IBaseView) getActivity(), data, new BaseHttpObserver<>() {
                 @Override
                 protected void handleResultOkResp(BaseResp resp) {
                     ToastUtil.showToast("创建成功");
                     refreshData();
                 }
             });
         });
        dialog.setEdInputFilter(new InputFilter[]{new InputFilter.LengthFilter(20)});

    }

    private ArrayList<Object> getOrderId() {
        ArrayList orderIds = new ArrayList();
        for (WaitToAccuntBean waitToAccuntBean : mChoices) {
            orderIds.add(waitToAccuntBean.getId());
        }
        return orderIds;
    }

    //勾选全选or取消全选后，更新ui
    private void updateView(boolean isAllCheck) {
        mChoices.clear();
        for (WaitToAccuntBean waitToAccuntBean : mDatas) {
            waitToAccuntBean.setmIsCheck(isAllCheck);
        }
        if (isAllCheck) {
            mChoices.addAll(mDatas);
        }
        notifyListDataSetChanged();
    }


    @Override
    protected HttpServicesHolder<?, BasePageData<WaitToAccuntBean>> getHttpServicesHolder(long index) {
        return new HttpServicesHolder<IReconciliationApi, BasePageData<WaitToAccuntBean>>() {
            @Override
            public Observable<BasePageData<WaitToAccuntBean>> getHttpObservable(IReconciliationApi api) {
                ArrayMap<String, Object> queryData = new ArrayMap<>();

                if (TextUtils.isEmpty(startTime)) {
                    startTime = DateTimeUtils.formatDateTime(System.currentTimeMillis(), DateTimeUtils.SHORT_DATETIME_FORMAT_STRING);
                    endTime = startTime + " 23:59:59";
                    startTime = startTime + " 00:00:00";
                }
                queryData.put("startTime", startTime);
                queryData.put("endTime", endTime);
                queryData.put("page",1);
                queryData.put("status",1);
                queryData.put("pageSize", Constant.DEFAULTPAGESIZE);
                queryData.put("customerId", customerId);
                return api.getWaitToAccunts(queryData);
            }
        };
    }
}
